﻿#include "redis_manager.h"

#include "multi_task/multi_task_mgr.h"
#include "log.h"
#include "redis_db_connection.h"

#include <boost/algorithm/string.hpp>

CRedisDbManager::CRedisDbManager()
{
	
}

CRedisDbManager::~CRedisDbManager()
{
}

bool CRedisDbManager::CreateDbConnectPool(const std::string &instName, const std::vector<std::string> &hosts, std::vector<unsigned> ports, const std::string &auth_database, const std::string &user, const std::string &pwd, const std::vector<std::pair<std::string, std::string>> &options)
{
	if (m_clients.find(instName) != m_clients.end())
	{
		return true;
	}
	unsigned connNum = MultiTask::Mgr::get_mutable_instance().GetThreadNum();
	auto &clients = m_clients.insert(std::make_pair(instName, InstSetType())).first->second;
	for (size_t i = 0; i < connNum; i++)
	{
		auto client = std::make_shared<CRedisDbConnection>();
		bool ret;/* = client->Connect(hosts, ports, auth_database, user, pwd, options);*/
		if (!ret)
		{
			LOG_ERROR_TO("RedisDbManager ", Fmt("crteate db instance failure, memory error"));
			m_clients.erase(instName);
			return false;
		}
		clients.emplace_back(client);
	}
	return true;
}

CRedisDbManager::InstSetType &CRedisDbManager::GetDbInstance(const std::string &instName)
{
	static InstSetType g_empty_inst;
	auto it = m_clients.find(instName);
	if (it == m_clients.end())
	{
		return g_empty_inst;
	}
	return it->second;
}

void CRedisDbManager::KeepAlive(int iS)
{
	m_connectionPool.KeepAlive(iS);
}

bool CRedisDbManager::Initialize(const std::string &instName, const std::string & host, const std::string & port_or_socket, const std::string & user, const std::string & password, const std::string& database)
{
	unsigned threadNum = MultiTask::Mgr::get_mutable_instance().GetThreadNum();
	auto &clients = m_clients.insert(std::make_pair(instName, InstSetType())).first->second;
	for (size_t i = 0; i < threadNum; i++)
	{
		auto client = std::make_shared<CRedisDbConnection>();
		bool ret = client->Connect(host, port_or_socket, database, user, password );
		if (!ret)
		{
			LOG_ERROR_TO("CRedisDbManager", Fmt("crteate db instance failure, memory error"));
			m_clients.erase(instName);
			return false;
		}
		clients.emplace_back(client);
	}
	return true;
}
